package com.wenjh.jdmzt.android.synctask;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import android.graphics.Bitmap;

import com.wenjh.jdmzt.AndroidKit;
import com.wenjh.jdmzt.util.Log4Android;
import com.wenjh.jdmzt.R;

public class ImageGC {
	private static BlockingQueue<Bitmap> queue = null;
	private static Log4Android log = new Log4Android("ImageGC");
	private static Thread worker = null;
	private static Recycler recycler = null;
	
	public static void run() {
		finish(); // 结束上一次的工作（如果有的话）

		queue = new LinkedBlockingQueue<Bitmap>();
		recycler = new Recycler(queue);
		
		worker = new Thread(recycler);
		worker.start();
	}
	
	public static void finish() {
		if(recycler != null) {
			recycler.finish();
			recycler = null;
		}
	}
	
	public static void put(Bitmap b) {
		if(b == null) {
			return;
		}
		
		if(queue == null) {
			run();
		}
		
		try {
			queue.put(b);
		} catch (InterruptedException e) {
			log.e(e);
		}
	}
	
	private static class Recycler implements Runnable {
		private BlockingQueue<Bitmap> queue = null;
		private boolean working = true;
		
		public Recycler(BlockingQueue<Bitmap> queue) {
			this.queue = queue;
		}
		
		/**
		 * 结束图片回收器的工作。结束之前，要确保队列里的图片都已经被回收。
		 */
		public void finish() {
			this.working = false;
			try {
				queue.put(AndroidKit.decodeBitmap(R.drawable.app_icon));
			} catch (InterruptedException e) {
			}
		}
		
		@Override
		public void run() {
			try {
				while (true && (working || queue.size() > 0)) {
					Bitmap b = queue.take();
					if(b != null) {
						b.recycle();
						b = null;
					}
				}
			} catch (InterruptedException e) {
			}
		}
	};
}
